<template>
  <div>
    <el-card>
      <el-form inline class="search_form">
        <el-form-item label="角色名：">
          <el-input placeholder="请输入角色名" v-model="searchName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getRoleList(1)" :disabled="tableLoading">搜索</el-button>
          <el-button type="primary" plain @click="searchName = ''" :disabled="!searchName">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table_box">
      <el-form inline>
        <el-form-item>
          <el-button type="primary" @click="handleAddRole">添加角色</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="tableLoading" :data="tableData" border style="margin: 10px 0; width: 100%">
        <el-table-column align="center" label="#" type="index" />
        <el-table-column align="center" label="id" prop="id" />
        <el-table-column align="center" label="角色名称" prop="roleName" show-overflow-tooltip />
        <el-table-column align="center" label="创建时间" prop="createTime" show-overflow-tooltip />
        <el-table-column align="center" label="更新时间" prop="updateTime" show-overflow-tooltip />
        <el-table-column align="center" label="操作" width="300px" class="btn_box">
          <template #="{ row }">
            <el-button type="primary" icon="user" size="small" @click="handleEditPermission(row)">分配权限</el-button>
            <el-button type="primary" icon="edit" size="small" @click="handleEditRole(row)">编辑</el-button>

            <el-popconfirm :title="`确认删除：${row.roleName}？`" width="200" @confirm="handleDelRole(row.id)">
              <template #reference>
                <el-button type="primary" icon="delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next,jumper, ->, sizes,total"
        :total="total"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10]"
        background
        @current-change="getRoleList"
        @size-change="handleSizeChange"
      />
    </el-card>
    <el-dialog
      v-model="showDialog"
      :title="roleId ? '编辑角色' : '新增角色'"
      width="40%"
      close-on-click-modal
      @close="handleClose"
    >
      <el-form :model="roleForm" ref="roleRef" :rules="roleRules">
        <el-form-item label="角色名：" prop="roleName">
          <el-input placeholder="请输入角色名" v-model="roleForm.roleName"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleDialogConfirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-drawer v-model="showDrawer" title="分配权限" direction="rtl" size="30%" @close="handleDrawerCancel">
      <template #default>
        <el-tree
          ref="treeRef"
          :props="menuProps"
          :data="menuData"
          :default-checked-keys="selectMenu"
          node-key="id"
          show-checkbox
          default-expand-all
        />
      </template>
      <template #footer>
        <el-button @click="showDrawer = false">取消</el-button>
        <el-button type="primary" @click="handleDrawerSave">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { reqRoleList, reqDelUser, reqAddRole, reqMenuList, reqSetRoleMunu } from "@/api/acl/role";
import { RoleResponseData, RoleData, MenuList, MenuResponseData, RoleSetMenuData } from "@/api/acl/role/type";
import { ElMessage } from "element-plus";

let tableLoading = ref<boolean>(false); // 控制表格加载动画
let tableData = ref<any>([]); // 表格数据
let total = ref<number>(0); // 表格总数
let pageNo = ref<number>(1); // 表格页
let pageSize = ref<number>(5); // 表格每页数量
let searchName = ref<string>(""); // 表格每页数量

let showDialog = ref<boolean>(false); // 控制新增/修改对话框显示
let roleId: number | undefined = undefined; // 当前操作的角色的id
const roleRef = ref(); // 获取输入表单实例
const roleForm = ref({
  roleName: ""
}); // 新建/编辑角色的名称
const roleRules: any = {
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }]
}; // 加入表单验证

let showDrawer = ref<boolean>(false); // 控制分配角色抽屉显示
let menuData = ref<MenuList>([]); // 菜单列表
let selectMenu = ref<number[]>([]); // 已分配的菜单
const menuProps = { label: "name", children: "children" }; // 树形结构展示字段
const treeRef = ref();
// ---------------------------------------//
onMounted(() => {
  getRoleList();
});
// --------------外部表格------------------------//
// 根据条件获取角色列表
const getRoleList = async (pager = 1) => {
  pageNo.value = pager;
  tableLoading.value = true;
  const res: RoleResponseData = await reqRoleList(pageNo.value, pageSize.value, searchName.value);
  // console.log(res);
  tableLoading.value = false;
  if (res.code === 200) {
    total.value = res.data.total;
    tableData.value = res.data.records;
  }
};
// 点击切换表格每页数量
const handleSizeChange = () => {
  getRoleList();
};
// ----------------添加/编辑/删除角色-----------------------//
// 添加角色点击
const handleAddRole = () => {
  showDialog.value = true;
};
// 编辑角色点击
const handleEditRole = (role: RoleData) => {
  // console.log(role);
  handleAddRole();
  roleId = role.id;
  roleForm.value.roleName = role.roleName;
};
// 弹窗确定
const handleDialogConfirm = async () => {
  await roleRef.value.validate();
  const data = {
    id: roleId,
    roleName: roleForm.value.roleName
  };
  const res: any = await reqAddRole(data);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "操作成功！"
    });

    getRoleList(pageNo.value);
    showDialog.value = false;
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// 关闭弹窗
const handleClose = () => {
  roleId = undefined;
  Object.assign(roleForm.value, { roleName: "" });
  roleRef.value.clearValidate();
};
// 点击确认删除
const handleDelRole = async (id: number) => {
  const res: any = await reqDelUser(id);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功！"
    });
    const page = tableData.value.length === 1 ? pageNo.value - 1 : pageNo.value;
    getRoleList(page || 1);
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// ----------------分配权限-----------------------//
// 点击编辑权限
const handleEditPermission = async (role: RoleData) => {
  showDrawer.value = true;
  roleId = role.id;
  const res: MenuResponseData = await reqMenuList(role.id as number);
  // console.log(res);

  if (res.code == 200) {
    menuData.value = res.data;
    selectMenu.value = filterSelect(res.data, []);
    // console.log(selectMenu.value);
  }
};
// 获取已选的菜单项
const filterSelect = (menuList: MenuList, arr: number[]) => {
  menuList.forEach(item => {
    if (item.children.length > 0) {
      arr = filterSelect(item.children, arr);
    } else {
      if (item.selected) {
        arr.push(item.id);
      }
    }
  });
  return arr;
};

// 抽屉确认
const handleDrawerSave = async () => {
  const checkArr = treeRef.value.getCheckedKeys();
  const halfCheckArr = treeRef.value.getHalfCheckedKeys();
  // console.log(roleId, checkArr, halfCheckArr);
  const data: RoleSetMenuData = {
    roleId: roleId as number,
    menuId: [...checkArr, ...halfCheckArr]
  };
  const res = await reqSetRoleMunu(data);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: "操作成功！"
    });
    window.location.reload();
    showDrawer.value = false;
  }
};
// 抽屉取消
const handleDrawerCancel = () => {
  menuData.value = [];
  selectMenu.value = [];
  roleId = undefined;
};
</script>

<style scoped lang="scss">
.search_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    margin: 0;
  }
}
.table_box {
  margin-top: 10px;
  .btn_box {
    display: flex;
    justify-content: space-around;
  }
}
</style>
